package org.jeecg.modules.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.permission.entity.*;
import org.jeecg.modules.permission.mapper.TestRoleMapper;
import org.jeecg.modules.permission.mapper.TestUserDepartMapper;
import org.jeecg.modules.permission.mapper.TestUserMapper;
import org.jeecg.modules.permission.mapper.TestUserRoleMapper;
import org.jeecg.modules.permission.service.ITestUserService;
import org.jeecg.modules.permission.vo.TestUserPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 测试用户表
 * @Author: jeecg-boot
 * @Date:   2022-03-02
 * @Version: V1.0
 */
@Service
public class TestUserServiceImpl extends ServiceImpl<TestUserMapper, TestUser> implements ITestUserService {

    @Autowired
    private TestUserMapper testUserMapper;

    @Autowired
    private TestUserRoleMapper testUserRoleMapper;

    @Autowired
    private TestUserDepartMapper testUserDepartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(TestUserPage user) {
        String userId = IdWorker.get32UUID();
        testUserMapper.insert(user.setId(userId));
        TestUserRole userRole = new TestUserRole(user, user.getRole());
        testUserRoleMapper.insert(userRole);
        TestUserDepart userDepart = new TestUserDepart(user, user.getDepart());
        testUserDepartMapper.insert(userDepart);
        return true;
    }

    @Override
    public boolean edit(TestUserPage user) {
        testUserMapper.updateById(user);
        TestRole role = user.getRole();
        if (role != null && role.getId() != null) {
            TestUserRole userRole = new TestUserRole(user, role);
            LambdaQueryWrapper<TestUserRole> query = new LambdaQueryWrapper<>();
            query.eq(TestUserRole::getUserId,user.getId());
            int i = testUserRoleMapper.update(userRole, query);
        }
        TestDepart depart = user.getDepart();
        if (depart != null && depart.getId() != null){
            TestUserDepart userDepart = new TestUserDepart(user, depart);
            LambdaQueryWrapper<TestUserDepart> query = new LambdaQueryWrapper<>();
            query.eq(TestUserDepart::getUserId,user.getId());
            testUserDepartMapper.update(userDepart,query);
        }
        return true;
    }

    @Override
    public List<TestUserPage> searchAll() {
        return testUserMapper.searchAll();
    }
}
